package collection.list;


public class MyLinkedList<T> {

    int size = 0;
    int end = 0;
    Node<T> nodeStart = new Node<T>(null, null, null);
    Node<T> node = nodeStart;

    //内部类Node，相当于一个节点
    //有前驱，值，后驱三个属性
    private static class Node<T> {
        T value;
        Node<T> prev;
        Node<T> next;

        public Node(Node<T> prev, T value, Node<T> next) {
            this.value = value;
            this.prev = prev;
            this.next = next;
        }

        public T getValue() {
            return value;
        }

        public void setValue(T value) {
            this.value = value;
        }
    }

    //无参构造
    public MyLinkedList() {
    }

    //添加新元素到末尾
    public void add(T element) {
        if (node == nodeStart) {
            Node<T> newNode = new Node<T>(nodeStart, element, null);
            nodeStart.next = newNode;
            node = newNode;
        } else {
            Node<T> newNode = new Node<T>(node, element, null);
            node.next = newNode;
            node = newNode;
        }
        size++;
        end++;
    }

    //添加新元素到指定位置
    public void add(int index, T element) {
        for (int i = 0; i < index - 1; i++) {
            node = node.next;
        }
        Node<T> newNode = new Node<>(node, element, node.next);
        node.next.prev = newNode;
        node.next = newNode;
    }

    //删除首元素
    public void deleteFirst() {
        nodeStart.next.next.prev = nodeStart;
        nodeStart.next = nodeStart.next.next;
        size--;
    }

    //删除尾元素
    public void deleteLast() {
        Node<T> node1 = nodeStart;
        for (int i = 0; i < size - 1; i++) {
            node1 = node1.next;
        }
        node1.next.prev = null;
        node1.next = null;
        size--;
    }

    //删除指定位置的元素
    public void delete(int index) {
        if (index == size - 1) {
            deleteLast();
        } else if (index == 0) {
            deleteFirst();
        } else {
            Node<T> node1 = nodeStart;
            for (int i = 0; i < index; i++) {
                node1 = node1.next;
            }
            node1.next.prev = node1.prev;
            node1.prev.next = node1.next;
        }
        size--;
    }

    //更改指定位置的元素
    public void update(int index, T element) {
        Node<T> node1 = nodeStart;
        for (int i = 0; i < index; i++) {
            node1 = node1.next;
        }
        node1.setValue(element);
    }


    //查指定位置的元素
    public T getByIndex(int index) {
        Node<T> node1 = nodeStart;
        for (int i = 0; i < index; i++) {
            node1 = node1.next;
        }
        return node1.getValue();
    }

    //重写toString方法
    @Override
    public String toString() {
        String message = "";
        Node<T> node1 = nodeStart.next;
        for (int i = 0; i < size; i++) {
            message = message + node1.value + "  ";
            node1 = node1.next;
        }
        return message;
    }
}
